//
//  HWButton.m
//  HMSDK
//
//  Created by hy on 2021/11/2.
//  Copyright © 2021 egret. All rights reserved.
//

#import "HWButton.h"


@interface HWButton ()

{

    NSInteger timerCount;

}

@property (nonatomic, strong) NSTimer *timerCoder;

@property (nonatomic) BOOL buttonEnabled;

@end

@implementation HWButton

- (void)startWithTimerCount:(NSInteger)count

{

    [self stopTimer];

    NSString *buttonTitle = [NSString stringWithFormat:@"%zd秒后重发",count];

    [self setButtonTitle:buttonTitle];

    self.buttonEnabled = NO;

    timerCount = count-1;

    _timerCoder = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

}

- (void)stopTimer

{

    if (_timerCoder) {

        [_timerCoder invalidate];

        _timerCoder = nil;

        self.buttonEnabled = YES;

    }

}

- (void)timerAction {

    if (timerCount > 0) {

        NSString *title = [NSString stringWithFormat:@"%zd秒后重发",timerCount];

        [self setButtonTitle:title];

    }else{

        [self stopTimer];

    }

    timerCount -= 1;

}

- (void)setButtonTitle:(NSString *)title {

    self.titleLabel.text = title;

    [self setTitle:title forState:UIControlStateNormal];

}

- (void)setButtonEnabled:(BOOL)buttonEnabled

{

    _buttonEnabled = buttonEnabled;

    if (buttonEnabled) {

        [self setButtonTitle:@"重新发送"];

        self.alpha = 1.0;

    }else{

        self.alpha = 0.5;

    }

    self.enabled = buttonEnabled;

}

- (void)dealloc {
    [self stopTimer];
}

@end
